/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-04-27 14:29:15
 * @LastEditTime : 2023-05-24 09:21:45
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Common\Modal\MoreModal\PPPBox.jsx
 * @Description  :
 */

import './PPPBox.scss'
import '../../Form/FormAssembly'
import { Http } from '../../Api'
import { Drawer, Button, Modal, Form, message } from 'antd'
import { SeeEnclosureModal } from '../Modal'
import { TwoAddBtn, ThrDeleteBtn } from '../options'
import { useEffect, useState, useCallback } from 'react'
import { useBoolean, useEventEmitter, useRequest } from 'ahooks'
import { FormItem } from '../../Form/FormAssembly'
import { commonTableList } from '../../Router/MenuNav/Common/common'

const addList = ['ProjectCompanyInfos', 'ProjectBuildList']
const deleteList = ['delOrganizationPppListAttachment', 'delOrganizationBuildListAttachment']
const putList = ['putOrganizationPppListAttachment', 'putOrganizationBuildListAttachment']
const orgList = ['organizationPppListUuid', 'organizationBuildListUuid']

export const PPPBox = ({ CurrentData, data, upDataEvent }) => {
    const [PPPList, setPPPList] = useState([])

    const { runAsync: getBadaStatOrganizationPppListTree } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            const list = res.pop()
            setPPPList([res, [list]])
        },
    })

    const { runAsync: getBadaStatOrganizationBuildListTree } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            let last = res.pop()
            res.splice(1, 0, last)
            setPPPList([res])
        },
    })

    const { runAsync: getOrganizationPppListAttachment } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setLeftData(res.list)
            LeftTrue()
        },
    })

    const { runAsync: getOrganizationBuildListAttachment } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setLeftData(res.list)
            LeftTrue()
        },
    })

    const GetData = useCallback(() => {
        const { dataType } = CurrentData
        const { organizationUuid, uuid } = data
        if (dataType === 0)
            getBadaStatOrganizationPppListTree({
                url: 'getBadaStatOrganizationPppListTree',
                data: { organizationUuid },
            })
        if (dataType === 1)
            getBadaStatOrganizationBuildListTree({
                url: 'getBadaStatOrganizationBuildListTree',
                data: { organizationUuid: organizationUuid || uuid },
            })
    }, [CurrentData, data, getBadaStatOrganizationPppListTree, getBadaStatOrganizationBuildListTree])

    const GetList = uuid => {
        const { dataType } = CurrentData
        if (dataType === 0)
            getOrganizationPppListAttachment({
                url: 'getOrganizationPppListAttachment',
                data: { organizationPppListUuid: uuid },
            })
        if (dataType === 1)
            getOrganizationBuildListAttachment({
                url: 'getOrganizationBuildListAttachment',
                data: { organizationBuildListUuid: uuid },
            })
    }

    useEffect(() => {
        GetData()
    }, [GetData])

    const OpenList = (uuid, TypeUUid, tableName, planAttachmentCount) => {
        setLeftTitle(tableName)
        setLeftUuid(uuid)
        setUpDataUuid(TypeUUid)
        setLeftLength(planAttachmentCount)
        GetList(TypeUUid)
    }

    const [LeftDrawer, { setTrue: LeftTrue, setFalse: LeftFalse }] = useBoolean(false)
    const [LeftTitle, setLeftTitle] = useState()
    const [LeftUuid, setLeftUuid] = useState()
    const [UpDataUuid, setUpDataUuid] = useState()
    const [LeftData, setLeftData] = useState([])
    const [LeftLength, setLeftLength] = useState()
    const [AttStatus, { setTrue: AttTrue, setFalse: AttFalse }] = useBoolean(false)
    const [AttData, setAttData] = useState()
    const [ModifyStatus, { setTrue: ModifyTrue, setFalse: ModifyFalse }] = useBoolean(false)
    const [AttUrl, setAttUrl] = useState()

    const PPPEvent = useEventEmitter()
    PPPEvent.useSubscription(() => {
        GetData()
        GetList(UpDataUuid)
    })

    return (
        <div className="PPPBox">
            <div className="PPPList">
                {PPPList.map((item, index) => (
                    <div key={index} className={index === 0 ? 'left' : 'right'}>
                        {item.map(({ uuid, tableName, children }) => (
                            <div key={uuid} className="List">
                                <div className="Title">{tableName}</div>
                                <div className="Content">
                                    {children.map(
                                        ({
                                            uuid,
                                            organizationBuildListUuid,
                                            organizationPppListUuid,
                                            tableName,
                                            isImportant,
                                            planAttachmentCount,
                                            completeAttachmentCount,
                                        }) => (
                                            <div
                                                className="Item"
                                                key={uuid}
                                                style={planAttachmentCount === 0 ? { color: '#999999' } : {}}
                                                onClick={() => {
                                                    if (planAttachmentCount === 0) return false
                                                    const { dataType } = CurrentData
                                                    if (dataType === 0)
                                                        OpenList(
                                                            uuid,
                                                            organizationPppListUuid,
                                                            tableName,
                                                            planAttachmentCount,
                                                        )
                                                    if (dataType === 1)
                                                        OpenList(
                                                            uuid,
                                                            organizationBuildListUuid,
                                                            tableName,
                                                            planAttachmentCount,
                                                        )
                                                }}
                                            >
                                                {isImportant ? <div>【重要节点】</div> : ''}
                                                <div>{tableName}</div>
                                                {planAttachmentCount !== 0
                                                    ? `( ${completeAttachmentCount}/${planAttachmentCount} )`
                                                    : ''}
                                            </div>
                                        ),
                                    )}
                                </div>
                            </div>
                        ))}
                    </div>
                ))}
            </div>

            {/* 打开左侧抽屉 */}
            {LeftDrawer && (
                <Drawer title={LeftTitle} width={600} placement="left" onClose={LeftFalse} open={LeftDrawer}>
                    <div className="LeftList">
                        {LeftData.length < LeftLength && (
                            <TwoAddBtn
                                upDataEvent={upDataEvent}
                                title="添加文件附件"
                                ThrKey="ThrModal"
                                value={addList[CurrentData.dataType]}
                                data={{ ...data, LeftUuid }}
                                PPPEvent={PPPEvent}
                            />
                        )}
                        {LeftData.map(item => (
                            <div className="AttItem" key={item.uuid}>
                                <div
                                    onClick={() => {
                                        setAttUrl({ url: item.attachment.fileUrl })
                                        AttTrue()
                                    }}
                                >
                                    {item.tableName}
                                </div>
                                <div>{item.sortId}</div>
                                <div>
                                    <Button
                                        type="link"
                                        onClick={() => {
                                            setAttData(item)
                                            ModifyTrue()
                                        }}
                                    >
                                        修改
                                    </Button>

                                    <ThrDeleteBtn
                                        key="delete"
                                        record={item.uuid}
                                        upDataEvent={upDataEvent}
                                        data={{
                                            key: 'delete',
                                            url: deleteList[CurrentData.dataType],
                                            title: '删除附件',
                                        }}
                                        PPPEvent={PPPEvent}
                                    />
                                </div>
                            </div>
                        ))}
                    </div>
                </Drawer>
            )}

            {/* 附件弹出层 */}
            {AttStatus && <SeeEnclosureModal data={AttUrl} Off={AttFalse} />}
            {ModifyStatus && (
                <PPPAttModify PPPEvent={PPPEvent} CurrentData={CurrentData} data={AttData} Off={ModifyFalse} />
            )}
        </div>
    )
}

const PPPAttModify = ({ PPPEvent, CurrentData, Off, data }) => {
    const [form] = Form.useForm()
    const { runAsync } = useRequest(Http, { manual: true, throttleWait: 1500 })
    const [SubmitStatus, { setTrue: SubmitTrue, setFalse: SubmitFalse }] = useBoolean(false)
    const [messageApi, contextHolder] = message.useMessage()

    const [PageData] = useState([
        commonTableList.uuid,
        {
            dataIndex: 'attachmentUuid',
            title: '项目概况',
            valueType: 'hidden',
            hideInSearch: true,

            width: 400,
        },
        {
            dataIndex: orgList[CurrentData.dataType],
            title: '项目概况',
            valueType: 'hidden',
            hideInSearch: true,

            width: 400,
        },
        { ...commonTableList.tableName, title: '名称' },
        { ...commonTableList.sortId },
    ])

    const Submit = e => {
        SubmitTrue()
        runAsync({ url: putList[CurrentData.dataType], data: e, path: [e.uuid] }).then(res => {
            messageApi.success('修改成功')
            PPPEvent.emit()
            Off()
            SubmitFalse()
        })
    }

    useEffect(() => {
        form.setFieldsValue(data)
    }, [data, form])

    return (
        <Modal
            className="ModalBox PPPBoxModal"
            open={true}
            footer={null}
            maskClosable={false}
            onCancel={Off}
            destroyOnClose
            title="修改附件信息"
            width={800}
            centered
        >
            {contextHolder}
            <Form className="FormAssembly" name="validateOnly" layout="vertical" onFinish={Submit} form={form}>
                <div className="FormList">
                    <FormItem form={form} PageData={PageData} />
                </div>
                <div className="FormSub">
                    <Form.Item>
                        <Button className="FormSubmit" type="primary" htmlType="submit" loading={SubmitStatus}>
                            提交
                        </Button>
                    </Form.Item>
                </div>
            </Form>
        </Modal>
    )
}
